<?php
namespace Home\Logic;
use Think;
vendor('WxpayAPI.lib.WxPay#Api');
include  VENDOR_PATH."WxpayAPI/lib/WxPay.Notify.php";

class NotifyLogic extends \WxPayNotify {
   
	//查询订单
	public function Queryorder($transaction_id)
	{
		$input = new \WxPayOrderQuery();
		$input->SetTransaction_id($transaction_id);
		$result = \WxPayApi::orderQuery($input);
		if(array_key_exists("return_code", $result)
			&& array_key_exists("result_code", $result)
			&& $result["return_code"] == "SUCCESS"
			&& $result["result_code"] == "SUCCESS")
		{
			return true;
		}
		return false;
	}

	//重写回调处理函数
	public function NotifyProcess($data, &$msg)
	{
		Think\Log::write(json_encode(print_r($data,true)));
		if(!array_key_exists("transaction_id", $data)){
			$msg = "输入参数不正确";
			Think\Log::write($msg);
			return false;
		}
		//查询订单，判断订单真实性
		if(!$this->Queryorder($data["transaction_id"])){
			$msg = "订单查询失败";
			Think\Log::write($msg);
			return false;
		}
        file_put_contents('log.txt','shuju:'.$data);
		$order_no = $data['attach']; // 订单号
		$transaction_id = $data['transaction_id'];
		//判断是否支付
		$is_transId = M('orders')->where(array('transaction_no'=>$transaction_id))->find();
		//判断订单是否存在
		$order=M('orders')->where("dingdan_temp = '%s'",array($order_no))->select();
		if(empty($is_transId) && !empty($order)){
            $info['transaction_no']=$transaction_id;  
            $info['status']=2;
            $info['paytime']=time();
            $info['status_type']='已支付,未发货';
            M('orders')->where('dingdan_temp='."'".$order_no."'")->save($info);
		}
		echo '<xml>
			   <return_code><![CDATA[SUCCESS]]></return_code>
			   <return_msg><![CDATA[OK]]></return_msg>
			</xml>';
		exit();
	}
}